import {
  AbpApplicationConfigurationServiceProxie,
  ApplicationConfigurationDto,
  CurrentUserDto,
} from '@/api/abp-service-proxies'
import { ServiceProxyConfig } from '@/api/AbpServiceBase'
import { defineStore } from 'pinia'

export const useApplicationConfigurationStore = defineStore('applicationConfiguration', {
  state: () => {
    return {
      applicationConfiguration: {} as ApplicationConfigurationDto,
    }
  },
  getters: {
    auth: (state) => state.applicationConfiguration.auth,
    currentTenant: (state) => state.applicationConfiguration.currentTenant,
    currentUser: (state) => state.applicationConfiguration.currentUser,
    localization: (state) => state.applicationConfiguration.localization,
    l: (state) => (key: string) => {
      const localization = state.applicationConfiguration.localization

      if (localization?.values && localization?.defaultResourceName) {
        return localization?.values[localization?.defaultResourceName][key] || key
      }

      return key
    },
  },
  actions: {
    initApplicationConfiguration(): Promise<ApplicationConfigurationDto> {
      if (this.applicationConfiguration.timing) {
        return Promise.resolve(this.applicationConfiguration)
      }

      const client = new AbpApplicationConfigurationServiceProxie(new ServiceProxyConfig())

      return client.applicationConfiguration().then((result) => {
        this.applicationConfiguration = result

        return Promise.resolve(this.applicationConfiguration)
      })
    },
    resetApplicationConfiguration(): Promise<ApplicationConfigurationDto> {
      this.applicationConfiguration.timing = undefined
      return this.initApplicationConfiguration()
    },
  },
})
